package com.kelvem.saas.workbanch.security.shiro;

import com.kelvem.saas.workbanch.core.exception.ErrorCodeEnum;
import com.kelvem.saas.workbanch.core.system.model.SysUserEntity;
import com.kelvem.saas.workbanch.core.utils.ServletUtils;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.BearerToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 鉴权登录拦截器
 **/
@Slf4j
public class JwtFilter extends RolesAuthorizationFilter {

    /**
     * 执行登录认证
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String bearer = httpRequest.getHeader(SecurityConstant.HEADER_STRING);
        if (bearer == null) {
            return false;
        }
        String token = bearer.startsWith(SecurityConstant.TOKEN_PREFIX) ? bearer.substring(7) : bearer;

        try {
            BearerToken jwtToken = new BearerToken(token);

            // 得到当前执行的用户
            Subject currentUser = SecurityUtils.getSubject();
            currentUser.login(jwtToken);

//            // 验证用户角色和权限
//            String[] rolesArray = (String[]) mappedValue;
//            for (String role : rolesArray) {
//                if (currentUser.hasRole(role)) {
//                    return true;
//                }
//            }
//            return false;

            String url = httpRequest.getRequestURI();
            url = this.converUrl(url);
            log.debug("JwtFilter.isAccessAllowed url, {}", url);

            SysUserEntity sysUser = (SysUserEntity) currentUser.getPrincipal();
            if ("admin".equals(sysUser.getUsername())) {
                return true;
            } else {
                currentUser.checkPermission(url);
            }
            return true;
        } catch (Exception e) {
            log.error("JwtFilter.isAccessAllowed error, " + e.getMessage(), e);
            return false;
        }
    }


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        ServletUtils.writeResponse(ErrorCodeEnum.ACCESS_DENIED, null);
        log.warn("JwtFilter.onAccessDenied, " + ((HttpServletRequest)request).getRequestURI());
        return false;
    }

    private String converUrl(String url) {
        if (url.startsWith("/bizPage/v1/get/")) {
            return url;
        }

        // 使用 matcher.replaceAll("") 替换匹配到的数字为空字符串
        Pattern pattern = Pattern.compile("/\\d+");
        Matcher matcher = pattern.matcher(url);
        url = matcher.replaceAll("");

        return url;
    }

}